package system_service

import (
	"errors"
	"fmt"
	"github.com/APP/global"
	"github.com/APP/internal/models"
	"gorm.io/gorm"
)

type PermissionService struct{}

// CreatePermission 创建权限
func (s *PermissionService) CreatePermission(req *models.PermissionCreateRequest) (*models.Permission, error) {
	// 检查权限代码是否已存在
	var existingPermission models.Permission
	if err := global.APP_DB.Where("code = ?", req.Code).First(&existingPermission).Error; err == nil {
		return nil, errors.New("权限代码已存在")
	}

	permission := &models.Permission{
		Name:        req.Name,
		Code:        req.Code,
		Type:        req.Type,
		Path:        req.Path,
		Method:      req.Method,
		Description: req.Description,
		ParentID:    req.ParentID,
		Sort:        req.Sort,
		Status:      req.Status,
	}

	if err := global.APP_DB.Create(permission).Error; err != nil {
		return nil, fmt.Errorf("创建权限失败: %v", err)
	}

	return permission, nil
}

// GetPermissionByID 根据ID获取权限
func (s *PermissionService) GetPermissionByID(id int64) (*models.Permission, error) {
	var permission models.Permission
	if err := global.APP_DB.First(&permission, id).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, errors.New("权限不存在")
		}
		return nil, fmt.Errorf("获取权限失败: %v", err)
	}
	return &permission, nil
}

// UpdatePermission 更新权限
func (s *PermissionService) UpdatePermission(id int64, req *models.PermissionUpdateRequest) (*models.Permission, error) {
	permission, err := s.GetPermissionByID(id)
	if err != nil {
		return nil, err
	}

	// 检查权限代码是否已被其他权限使用
	if req.Code != "" && req.Code != permission.Code {
		var existingPermission models.Permission
		if err := global.APP_DB.Where("code = ? AND id != ?", req.Code, id).First(&existingPermission).Error; err == nil {
			return nil, errors.New("权限代码已存在")
		}
	}

	// 更新字段
	if req.Name != "" {
		permission.Name = req.Name
	}
	if req.Code != "" {
		permission.Code = req.Code
	}
	if req.Type != "" {
		permission.Type = req.Type
	}
	if req.Path != "" {
		permission.Path = req.Path
	}
	if req.Method != "" {
		permission.Method = req.Method
	}
	if req.Description != "" {
		permission.Description = req.Description
	}
	permission.ParentID = req.ParentID
	permission.Sort = req.Sort
	permission.Status = req.Status

	if err := global.APP_DB.Save(permission).Error; err != nil {
		return nil, fmt.Errorf("更新权限失败: %v", err)
	}

	return permission, nil
}

// DeletePermission 删除权限
func (s *PermissionService) DeletePermission(id int64) error {
	permission, err := s.GetPermissionByID(id)
	if err != nil {
		return err
	}

	// 检查是否有子权限
	var childCount int64
	if err := global.APP_DB.Model(&models.Permission{}).Where("parent_id = ?", id).Count(&childCount).Error; err != nil {
		return fmt.Errorf("检查子权限失败: %v", err)
	}
	if childCount > 0 {
		return errors.New("存在子权限，无法删除")
	}

	// 检查是否有角色关联
	var roleCount int64
	if err := global.APP_DB.Table("sys_role_permissions").Where("permission_id = ?", id).Count(&roleCount).Error; err != nil {
		return fmt.Errorf("检查角色关联失败: %v", err)
	}
	if roleCount > 0 {
		return errors.New("权限已被角色使用，无法删除")
	}

	if err := global.APP_DB.Delete(permission).Error; err != nil {
		return fmt.Errorf("删除权限失败: %v", err)
	}

	return nil
}

// GetPermissionList 获取权限列表
func (s *PermissionService) GetPermissionList(req *models.PermissionListRequest) (*models.PermissionListResponse, error) {
	var permissions []models.Permission
	var total int64

	// 构建查询条件
	query := global.APP_DB.Model(&models.Permission{})

	if req.Name != "" {
		query = query.Where("name LIKE ?", "%"+req.Name+"%")
	}
	if req.Code != "" {
		query = query.Where("code LIKE ?", "%"+req.Code+"%")
	}
	if req.Type != "" {
		query = query.Where("type = ?", req.Type)
	}
	if req.Status != nil {
		query = query.Where("status = ?", *req.Status)
	}

	// 获取总数
	if err := query.Count(&total).Error; err != nil {
		return nil, fmt.Errorf("获取权限总数失败: %v", err)
	}

	// 分页查询
	if req.Page <= 0 {
		req.Page = 1
	}
	if req.PageSize <= 0 {
		req.PageSize = 10
	}

	offset := (req.Page - 1) * req.PageSize
	if err := query.Order("sort ASC, id ASC").Offset(offset).Limit(req.PageSize).Find(&permissions).Error; err != nil {
		return nil, fmt.Errorf("获取权限列表失败: %v", err)
	}

	// 转换为响应格式
	var permissionResponses []models.PermissionResponse
	for _, permission := range permissions {
		permissionResponses = append(permissionResponses, models.PermissionResponse{
			ID:          permission.ID,
			CreatedAt:   permission.CreatedAt,
			UpdatedAt:   permission.UpdatedAt,
			Name:        permission.Name,
			Code:        permission.Code,
			Type:        permission.Type,
			Path:        permission.Path,
			Method:      permission.Method,
			Description: permission.Description,
			ParentID:    permission.ParentID,
			Sort:        permission.Sort,
			Status:      permission.Status,
		})
	}

	return &models.PermissionListResponse{
		List:  permissionResponses,
		Total: total,
		Page:  req.Page,
		Size:  req.PageSize,
	}, nil
}

// GetPermissionTree 获取权限树
func (s *PermissionService) GetPermissionTree() ([]models.PermissionResponse, error) {
	var permissions []models.Permission
	if err := global.APP_DB.Order("sort ASC, id ASC").Find(&permissions).Error; err != nil {
		return nil, fmt.Errorf("获取权限列表失败: %v", err)
	}

	// 转换为响应格式
	var permissionMap = make(map[int64]*models.PermissionResponse)
	var rootPermissions []models.PermissionResponse

	// 先创建所有权限节点
	for _, permission := range permissions {
		permissionResponse := models.PermissionResponse{
			ID:          permission.ID,
			CreatedAt:   permission.CreatedAt,
			UpdatedAt:   permission.UpdatedAt,
			Name:        permission.Name,
			Code:        permission.Code,
			Type:        permission.Type,
			Path:        permission.Path,
			Method:      permission.Method,
			Description: permission.Description,
			ParentID:    permission.ParentID,
			Sort:        permission.Sort,
			Status:      permission.Status,
			Children:    []models.PermissionResponse{},
		}
		permissionMap[permission.ID] = &permissionResponse
	}

	// 构建树形结构
	for _, permission := range permissions {
		if permission.ParentID == 0 {
			// 根节点
			rootPermissions = append(rootPermissions, *permissionMap[permission.ID])
		} else {
			// 子节点
			if parent, exists := permissionMap[permission.ParentID]; exists {
				parent.Children = append(parent.Children, *permissionMap[permission.ID])
			}
		}
	}

	return rootPermissions, nil
}

// GetPermissionsByRoleID 根据角色ID获取权限列表
func (s *PermissionService) GetPermissionsByRoleID(roleID int64) ([]models.Permission, error) {
	var permissions []models.Permission
	if err := global.APP_DB.Joins("JOIN sys_role_permissions ON sys_permissions.id = sys_role_permissions.permission_id").
		Where("sys_role_permissions.role_id = ?", roleID).
		Find(&permissions).Error; err != nil {
		return nil, fmt.Errorf("获取角色权限失败: %v", err)
	}
	return permissions, nil
}

// BatchDeletePermissions 批量删除权限
func (s *PermissionService) BatchDeletePermissions(ids []int64) error {
	// 检查是否有子权限
	var childCount int64
	if err := global.APP_DB.Model(&models.Permission{}).Where("parent_id IN ?", ids).Count(&childCount).Error; err != nil {
		return fmt.Errorf("检查子权限失败: %v", err)
	}
	if childCount > 0 {
		return errors.New("存在子权限，无法删除")
	}

	// 检查是否有角色关联
	var roleCount int64
	if err := global.APP_DB.Table("sys_role_permissions").Where("permission_id IN ?", ids).Count(&roleCount).Error; err != nil {
		return fmt.Errorf("检查角色关联失败: %v", err)
	}
	if roleCount > 0 {
		return errors.New("权限已被角色使用，无法删除")
	}

	if err := global.APP_DB.Where("id IN ?", ids).Delete(&models.Permission{}).Error; err != nil {
		return fmt.Errorf("批量删除权限失败: %v", err)
	}

	return nil
}
